package br.com.sglf.support;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "converterDouble")
public class ConverterDouble  implements Converter{

    /* (non-Javadoc)
     * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
     */
    public Object getAsObject(FacesContext context, UIComponent component, String value) {  
    	 
    	 
		if (value == null || (value.trim().length() == 0)) {  
			return new Double(0);  
		}  
    	 
		
		if(!SglfUtils.isNumerico(value.trim().replace(",", ""))){ 
			return new Double(0);   
		}
 
		if((new Double(value.trim().replace(",", "."))).intValue() > 100){ 
			return new Double(100D);   
		}
		
        return new Double(value.trim().replace(",", ".")); 
    }  
  
    /* (non-Javadoc)
     * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
     */
    public String getAsString(FacesContext context, UIComponent component, Object value) {  
  
         if (value == null) {  
            return "0,0";  
         }   
         if(value instanceof Double){  
        	 Double v = (Double) value;   
        	 
        	 return v.toString().replace(".", ",");     
         }else{  
             throw new IllegalArgumentException(  
                     "Objeto: " + value + "do tipo: " + value.getClass().getName());  
         }  
    }   
}
